package Service;

import Utils.DbUtil;
import dto.Table;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class GetTableService {


    public Table GetTableService(HttpServletRequest req, HttpServletResponse resp, String tableName) throws SQLException, ServletException, IOException {
        Connection conn = DbUtil.getConnection(req);
        ResultSet rs = null;
        DatabaseMetaData metaData = conn.getMetaData();
        List<Table> tablesList = new ArrayList<Table>();

        Statement stmt = conn.createStatement();
        try {
            rs = stmt.executeQuery("SELECT * FROM " + tableName);
        } catch (SQLException e) {
            req.setAttribute("error", e.getMessage());
            RequestDispatcher rd = req.getRequestDispatcher("error.jsp");
            rd.forward(req, resp);
        }
        ResultSetMetaData rsmd = rs.getMetaData();
        int numColumns = rsmd.getColumnCount();
        List<String> columns = new ArrayList<String>();
        for (int i = 1; i <= numColumns; i++) {
            columns.add(rsmd.getColumnName(i));
        }
        List<List<Object>> lists = new ArrayList<List<Object>>();
        while (rs.next()) {
            List<Object> data = new ArrayList<Object>();
            for (int i = 1; i <= numColumns; i++) {
                data.add(rs.getObject(i));
            }
            lists.add(data);
        }
        Table table = new Table(tableName, columns, lists);
        return table;
    }
}